package cn.lg.soar.core.util;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author luguoxiang 469599794@qq.com
 * @Date: 2025/5/18 11:01
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface FeignSecretUtils {

    String RANDOM_KEY = "security-random";
    String EXPIRE_KEY = "security-expire";
    String SIGN_KEY = "security-sign";
    /**
     * 有效期
     */
    int EXPIRE = 120_000;
    String HMAC_SHA256 = "HmacSHA256";
    Base64.Encoder BASE64EN = Base64.getEncoder();

    static String sign(SecretKeySpec keySpec, String userInfo, String random, String expire) {
        Mac mac;
        try {
            mac = Mac.getInstance(HMAC_SHA256);
            mac.init(keySpec);
        } catch (InvalidKeyException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        String str = (userInfo == null ? "" : userInfo) +"."+ random +"."+ expire;
        byte[] bytes = mac.doFinal(str.getBytes(StandardCharsets.UTF_8));
        return BASE64EN.encodeToString(bytes);
    }

    static boolean verify(SecretKeySpec keySpec, String userInfo, String random, String expire, String sign) {
        return sign(keySpec, userInfo, random, expire).equals(sign);
    }

    static SecretKeySpec getKeySpec(String secret) {
        return new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256);
    }
}
